package com.tssm.core.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 对cookie读写
 * 
 * @author 徐龙
 * 
 */
public class CookieUtils {
	public static final String DEFAULT_COOKIE_DOMAIN = "wwwtssmcom";// 设置你自己的域名
	public static final String DEFAULT_COOKIE_PATH = "/"; // 设置你自己的域名的地址
	public static String cookieDomain = DEFAULT_COOKIE_DOMAIN;
	public static String cookiePath = DEFAULT_COOKIE_PATH;

	/**
	 * 获取COOKIE
	 * 
	 * @param request
	 *            HttpServletRequest对象
	 * @param name
	 *            cookie名称
	 * @return
	 */
	public static Cookie getCookie(HttpServletRequest request, String name) {
		Cookie[] cookies = request.getCookies();
		if (cookies == null)
			return null;
		for (int i = 0; i < cookies.length; i++) {
			if (cookies[i].getName().equals(name)) {
				return cookies[i];
			}
		}
		return null;
	}

	/**
	 * 设置COOKIE
	 * 
	 * @param response
	 *            HttpServletResponse对象
	 * @param name
	 *            cookie名称
	 * @param value
	 *            cookie的值
	 * @param maxAge
	 *            最长时间
	 */
	public static void setCookie(HttpServletResponse response, String name,
			String value, int maxAge) {
		Cookie cookie = new Cookie(name, value);
		cookie.setMaxAge(maxAge);
		if (cookieDomain != null && cookieDomain.indexOf('.') != -1) {
			cookie.setDomain('.' + cookieDomain);
		}
		cookie.setPath(cookiePath);
		response.addCookie(cookie);
	}

	/**
	 * 修改COOKIE的值
	 * 
	 * @param request
	 *            HttpServletRequest对象
	 * @param response
	 *            HttpServletResponse对象
	 * @param name
	 *            cookie名称
	 * @param value
	 *            cookie的值
	 * @param maxAge
	 *            最长时间
	 */
	public static void setCookie(HttpServletRequest request,
			HttpServletResponse response, String name, String value) {
		Cookie cookie = getCookie(request, name);
		if (cookie != null) {
			cookie.setValue(value);
			response.addCookie(cookie);
		}
	}
}
